package com.sfh.base.http.server;

import android.net.ParseException;

import com.google.gson.JsonParseException;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;

import java.io.IOException;
import java.net.ConnectException;
import java.util.Arrays;
import java.util.List;

import retrofit2.HttpException;

/**
 * 功能描述:异常统一处理信息
 *
 * @date 2017/6/6
 */
public final class ExceptionHandle {

    private static final List<Integer> NET_ERROR_CODE = Arrays.asList (401, 403, 404, 408, 500, 502, 503, 504);


    public static ResponeThrowable handleException(Throwable e) {

        if (e == null) {
            return new ResponeThrowable (new NullPointerException ("null Object"), Error.HTTP);
        }

        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            if (NET_ERROR_CODE.contains (httpException.code ())) {
                return new ResponeThrowable (e, Error.HTTP);
            }
        }
        if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            return new ResponeThrowable (e, Error.PARSE);
        }

        if (e instanceof ConnectException) {
            return new ResponeThrowable (e, Error.NETWORD);
        }

        if (e instanceof javax.net.ssl.SSLHandshakeException) {
            return new ResponeThrowable (e, Error.SSL);
        }

        if (e instanceof ConnectTimeoutException || e instanceof java.net.SocketTimeoutException) {
            return new ResponeThrowable (e, Error.TIMEOUT);
        }
        if (e instanceof IOException) {
            return new ResponeThrowable (e, Error.IO);
        } else {
            return new ResponeThrowable (e, Error.UNKNOWN);
        }
    }

    public enum Error {

        UNKNOWN (1000, "未知错误"),
        PARSE (1001, "解析错误"),
        NETWORD (1002, "网络错误"),
        HTTP (1003, "协议出错"),
        SSL (1004, "证书出错"),
        TIMEOUT (1005, "连接超时"),
        IO (1006, "IO错误");

        public int code;

        public String msg;

        Error(int coe, String msg) {

            this.code = coe;
            this.msg = msg;
        }
    }

    /***
     *
     */
    public static class ResponeThrowable extends RuntimeException {

        public String code;

        public String message;

        public ResponeThrowable(Throwable throwable, int code) {

            super (throwable);
            this.code = String.valueOf (code);

        }

        public ResponeThrowable(Throwable throwable, Error error) {

            super (throwable);
            this.code =String.valueOf (error.code) ;
            this.message = error.msg;
        }

        public String getCode() {

            return code;
        }

        @Override
        public String getMessage() {

            return message;
        }
    }

}
